import { defineStore } from 'pinia'
import { UserState } from '@/store/modules/type.ts'
import {
  loginFormData,
  loginResponseData,
  userInfoReponseData,
} from '@/api/user/type.ts'
import { reqLogin, reqUserInfo, outLogin } from '@/api/user/index.ts'
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes.ts'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
function filterAsyncRoute(asyncRoutes: any, routes: any) {
  return asyncRoutes.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
let useUserStore = defineStore('User', {
  // 存储数据
  state: (): UserState => {
    return {
      token: localStorage.getItem('TOKEN'),
      router: constantRoute,
      username: '',
      avatar: '',
      buttons: [],
    }
  },
  // 异步|逻辑
  actions: {
    async userLogin(data: loginFormData) {
      let res: loginResponseData = await reqLogin(data)
      if (res.code == 200) {
        this.token = res.data as string
        localStorage.setItem('TOKEN', res.data as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },
    async getUserInfo() {
      let res: userInfoReponseData = await reqUserInfo()
      if (res.code == 200) {
        this.username = res.data.name
        this.avatar = res.data.avatar
        this.buttons = res.data.buttons
        // 动态路由的添加 cloneDeep深拷贝以防数据改动
        const userAsyncRoute = filterAsyncRoute(
          cloneDeep(asyncRoute),
          res.data.routes,
        )
        this.router = [...constantRoute, ...userAsyncRoute, anyRoute]
        let menuRoutes = [...userAsyncRoute, anyRoute]
        menuRoutes.forEach((item) => {
          router.addRoute(item)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async logOut() {
      let res: any = await outLogin()
      if (res.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        localStorage.removeItem('TOKEN')
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})
export default useUserStore
